<?php

	class income {
		

		function income() {
		global $admin,$db,$config;
			if ($_POST['act']=='export'){
			    $params=$_GET;
			   $sqlstr = "select a.id,a.shop,c.title,b.pid,a.productid,a.product,d.barcode,a.lotnumber,a.spec,a.unit,a.timeend,a.number,a.type,a.timeexpress,a.timestocked,a.puser,a.suser from {$config->db_prefix}purchases as a left join haiou_product_sku as b on a.productid=b.id left join {$config->db_prefix}purchases_paper as c on a.paper_id=c.id left join {$config->db_prefix}products as d on a.productid=d.product_sku_id where (c.status=2 or c.status=9 or c.status is null)";
			if (!empty($params['id'])) $sqlstr .= " and id = ".$db->qstr($params['id']);
			if (!empty($params['product_id'])) $sqlstr .= " and b.pid in(".trim($params['product_id']).")";
			if (!empty($params['shopid'])) $sqlstr .= " and shopid = ".$db->qstr($params['shopid']);
			if (!empty($params['keywords'])) $sqlstr .= " and b.pname like ". $db->qstr("%".$params['keywords']."%");
			if (!empty($params['sdate'])) $sqlstr .= " and thedate>=". strtotime($params['sdate']);
			if (!empty($params['edate'])) $sqlstr .= " and thedate<=". (strtotime($params['edate'])+86399);
			if (!empty($params['lprice'])) $sqlstr .= " and pricebuy>=". $db->qstr($params['lprice']);
			if (!empty($params['hprice'])) $sqlstr .= " and pricebuy<=". $db->qstr($params['hprice']);
			if (!empty($params['lnumber'])) $sqlstr .= " and number>=". $db->qstr($params['lnumber']);
			if (!empty($params['hnumber'])) $sqlstr .= " and number<=". $db->qstr($params['hnumber']);
			
			if (!empty($params['supplier'])) $sqlstr .= " and supplier like ". $db->qstr("%".$params['supplier']."%");
				
			if (!empty($params['lotnumber'])) $sqlstr .= " and lotnumber like ". $db->qstr("%".$params['lotnumber']."%");
			if (!empty($params['barcode'])) $sqlstr .= " and d.barcode=".$db->qstr($params['barcode']);
			if (!empty($params['sdate1'])) $sqlstr .= " and timeexpress>=". strtotime($params['sdate1']);
			if (!empty($params['edate1'])) $sqlstr .= " and timeexpress<=". strtotime($params['edate1']);
			if (!empty($params['sdate2'])) $sqlstr .= " and timeend>=". strtotime($params['sdate2']);
			if (!empty($params['edate2'])) $sqlstr .= " and timeend<=". strtotime($params['edate2']);
			if (!empty($params['sdate3'])) $sqlstr .= " and timestocked>=". strtotime($params['sdate3']);
			if (!empty($params['edate3'])) $sqlstr .= " and timestocked<=". strtotime($params['edate3']);
				
			
			if (!empty($params['cond'])) $sqlstr .= " and ({$params['cond']})";
			
			if($params['type']!==null&&$params['type']!==''){
			     $sqlstr .= " and type= {$params['type']}";
			}
			if($params['status']==''){
				$params['status'] = '0';
			}
			if($params['status']==="0"){
			    $sqlstr .= " and timestocked= 0";
			}elseif ($params['status']==="1"){
			    $sqlstr .= " and timestocked> 0";
			}elseif ($params['status']==="-1"){
			    $sqlstr .= " and timestocked= -1";
			}
				
			
// 			if (!empty($params['counter'])) $counter = $db->getrow(str_replace("*", "sum(number) number, sum(pricebuy*number) price", $sqlstr));
			if (!empty($params['order'])) $sqlstr .= " order by {$params['order']}";
			    include_once '../lib/php_excel.php';
			    $export_data=$db->GetArray($sqlstr);
			    foreach ($export_data as $kk=>$vv)
			    {
			    	$export_data[$kk]['type'] = $config->product_type[$vv['type']];
			    	$export_data[$kk]['timeend'] = ($vv['timeend']>0)?date("Y-m-d H:i:s",$vv['timeend']):"";
			    	$export_data[$kk]['timeexpress'] = ($vv['timeexpress']>0)?date("Y-m-d H:i:s",$vv['timeexpress']):"";
			    	$export_data[$kk]['timestocked'] = ($vv['timestocked']>0)?date("Y-m-d H:i:s",$vv['timestocked']):"";
			    	$export_data[$kk]['incomeStatus'] = ($vv['timestocked']==-1)?"未入库":(($vv['timestocked']>0)?"已入库":(($vv['timestocked']==0)?"未处理":"未知"));
			    }
			    $queue[0] = array("序号","仓库","采购单","产品ID","SKU_ID","产品名称","条码","批号","规格","单位","保质期","入库数量","入库类型","到货时间","入库时间","采购员"," 入库员","状态");//定义表头
			    $export_data = array_merge($queue,$export_data);
			   /*  print_r($export_data);
			    exit; */
			    $filename =   "入库信息" . date ( "YmdHis" );
			    $xls = new Excel_XML ( 'UTF-8', false, '入库信息' );
			    $xls->addArray ( $export_data );
			    $xls->generateXML ( $filename );
			    exit ();
			}

			//if(empty($_SESSION["managerid"])) $admin->login();
		}
		
		function index() {
			global $admin,$config,$smarty;
			$smarty->assign('type',$config->product_type);
			//if(!$admin->rights("purchases_view")) return;
		}


		function create() {
			global $db, $smarty, $config, $segment, $admin;
			//if(!$admin->rights("purchases_create")) return;
			unset($config->product_type[0]);
			$smarty->assign('type',$config->product_type);
			
			//过期时间和到货时间起始结尾值
			$year = date('Y');
			$start_year = $year - 5;
			$end_year = $year + 5;
			$smarty->assign('start_year',$start_year);
			$smarty->assign('end_year',$end_year);
			
			if(!empty($_POST["action"]) && $_POST["action"]=="create") {

				$timeexpress = strtotime($_POST["Date_Year"]."-".$_POST["Date_Month"]."-".$_POST["Date_Day"]);
// 				$timestart = strtotime($_POST["start_Year"]."-".$_POST["start_Month"]."-".$_POST["start_Day"]);
				$timestart = 0;
				$timeendTemp = $_POST["end_Year"]."-".$_POST["end_Month"]."-".$_POST["end_Day"];
				$timeend = strtotime($_POST["end_Year"]."-".$_POST["end_Month"]."-".$_POST["end_Day"]);
				
				
				$smarty->assign("timeexpress", $timeexpress);
				
				if(empty($_POST["shopid"])) $errors["empty_shopid"] = true;
				if(empty($_POST["product"])) $errors["empty_product"] = true;
				if(empty($_POST["number"]) || $_POST["number"]==0) $errors["empty_number"] = true;
// 				if(empty($_POST['lotnumber']))$errors['empty_lotnumber'] =true;
// 				if(empty($_POST['usedby']))$errors['empty_usedby'] =true;
                if($timeendTemp == date('Y-m-d')) $errors['endtime_error'] = true;
				
			
				
				$productid = $db->qstr($_POST["productid"]);
				$pro_info=$db->GetArray("select id from {$config->db_prefix}products where product_sku_id=$productid");
				if(empty($errors)) if(empty($pro_info)) $errors["unexist_product"] = true;
				if(empty($errors)) {
					$shopid = $db->qstr($_POST["shopid"]);
					$shop = $db->qstr($db->getone("select title from {$config->db_prefix}shops where id=$shopid"));
					$product = $db->qstr($_POST["product"]);
					$spec = $db->qstr($_POST["spec"]);
					$pricebuy = $db->qstr(empty($_POST["pricebuy"])?0:$_POST["pricebuy"]);
					$unit = $db->qstr($_POST["unit"]);
					$number = $db->qstr($_POST["number"]);
					$memo = $db->qstr($_POST["memo"]);
					$supplier = $db->qstr($_POST["supplier"]);
					$supplierid = empty($_POST["supplierid"])?0:$db->qstr($_POST["supplierid"]);
					$barcode = $_POST['barcode'];
					
					$lotnumber = $db->qstr($_POST["lotnumber"]);
					
					$type = $db->qstr($_POST["type"]);
						
// 					$usedby='+'.$_POST['usedby'].$_POST['usedbyunit'];
						
// 					$timeend=strtotime($usedby,$timestart);
						
// 					$usedby= $db->qstr($usedby);
					
					//echo date('Y-m-d',$endtime);
					$puser=$db->qstr($_SESSION['ADMIN_USER']);
					
					
					$sqlstr = "insert into {$config->db_prefix}purchases (shopid, shop, productid, product, spec, unit, pricebuy, number, supplierid, supplier, memo, timeexpress,lotnumber,timestart,timeend,type,puser ) values ($shopid, $shop, $productid, $product, $spec, $unit, $pricebuy, $number, $supplierid, $supplier, $memo, $timeexpress,$lotnumber,$timestart,$timeend,$type,$puser  )";
					$result = $db->execute($sqlstr);
					
					if($result){
						if($barcode){
							//更新商品条码
							$sql = "update {$config->db_prefix}products set barcode='{$barcode}' where product_sku_id=$productid";
							$db->execute($sql);
						}
						header("location:{$config->site_admin}m=inventory&s=income.php");
					}
				}
								
				if(!empty($errors)) $smarty->assign("errors", $errors);								
			}
		}
		
		
		function modify() {
			global $db, $smarty, $config, $segment, $admin;
			//if(!$admin->rights("purchases_modify")) return;
			
			//过期时间和到货时间起始结尾值
			$year = date('Y');
			$start_year = $year - 5;
			$end_year = $year + 5;
			$smarty->assign('start_year',$start_year);
			$smarty->assign('end_year',$end_year);
			
			if(!empty($_POST["action"]) && $_POST["action"]=="modify") {
				$timeexpress = strtotime($_POST["Date_Year"]."-".$_POST["Date_Month"]."-".$_POST["Date_Day"]);
// 				$timestart = strtotime($_POST["start_Year"]."-".$_POST["start_Month"]."-".$_POST["start_Day"]);
				$timeendTemp = $_POST["end_Year"]."-".$_POST["end_Month"]."-".$_POST["end_Day"];
				$timeend = strtotime($_POST["end_Year"]."-".$_POST["end_Month"]."-".$_POST["end_Day"]);
				
				$smarty->assign("timeexpress", $timeexpress);
				
				
				
				if(empty($_POST["shopid"])) $errors["empty_shopid"] = true;
				if(empty($_POST["product"])) $errors["empty_product"] = true;
// 				if(empty($_POST['lotnumber']))$errors['empty_lotnumber'] =true;
// 				if(empty($_POST['usedby']))$errors['empty_usedby'] =true;
				if($timeendTemp == date('Y-m-d')) $errors['endtime_error'] = true;
				
				
// 				$productid = $db->qstr($_POST["productid"]);
				
				
				
				//var_dump($errors);
// 				if(empty($errors)) if(!$db->getone("select count(1) from {$config->db_prefix}products where id=$productid")) $errors["unexist_product"] = true;

				if(empty($errors)) {
					$id = $db->qstr($_POST["id"]);
					$shopid = $db->qstr($_POST["shopid"]);
					$shop = $db->qstr($db->getone("select title from {$config->db_prefix}shops where id=$shopid"));
					$product = $db->qstr($_POST["product"]);
					$spec = $db->qstr($_POST["spec"]);
					$unit = $db->qstr($_POST["unit"]);
					$memo = $db->qstr($_POST["memo"]);
					$barcode = $_POST['barcode'];
					
					$lotnumber = $db->qstr($_POST["lotnumber"]);
					
// 					$usedby='+'.$_POST['usedby'].$_POST['usedbyunit'];
					
// 					$timeend=strtotime($usedby,$timestart);
					
// 					$usedby= $db->qstr($usedby);
					
					//echo date('Y-m-d',$endtime);
					$sqlstr = "update {$config->db_prefix}purchases set shopid=$shopid, shop=$shop, product=$product, spec=$spec, unit=$unit, lotnumber=$lotnumber, timeend=$timeend, memo=$memo, timeexpress=$timeexpress where id=$id";

					$result = $db->execute($sqlstr);
					if($barcode){
						$psql = "select productid from {$config->db_prefix}purchases where id=$id";
						$productid = $db->getone($psql);
						//更新商品条码
						$sql = "update {$config->db_prefix}products set barcode='{$barcode}' where product_sku_id=$productid";
						$db->execute($sql);
					}
					header("location:".(empty($_POST["referer"])?"{$config->site_admin}m=inventory&s=income.php":$_POST["referer"]."&page=".$_POST['list_page']));
				}
								
				if(!empty($errors)) $smarty->assign("errors", $errors);								
			}
			
		}


		function remove() {
			global $db, $segment, $config, $admin;
			//if(!$admin->rights("purchases_delete")) return;

			$id = $db->qstr($_GET['purchases_id']);
			$rss = $db->getrow("select paper_id from {$config->db_prefix}purchases where id=$id");
			
			$sqlstr = "delete from {$config->db_prefix}purchases where id=$id";
			$result = $db->execute($sqlstr);
			
			$this->update_paper_status($id,$rss['paper_id']);//判断是否全部入库并更新采购单状态
			
			if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=income.php":$_SERVER['HTTP_REFERER']));
		}
		
		
		function stockconfirm(){
		    global $db, $segment, $config, $smarty;
		    //批量入库
		    if($_POST['act'] && $_POST['act']=='op' && !empty($_POST['chk'])){
		    	foreach ($_POST['chk'] as $purchaseid)
		    	{
		    		$this->stockconfirm_one($purchaseid);
		    	}
		    }else{//单个入库
			    $purchaseid = $db->qstr($_GET['purchases_id']);
			    $result = $this->stockconfirm_one($purchaseid);
		    }
	        header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=income.php":$_SERVER['HTTP_REFERER']));
		}
		//入库一个商品
		private function stockconfirm_one($purchaseid){
			global $db, $segment, $config, $smarty;
			$rss = $db->getrow("select * from {$config->db_prefix}purchases where id=$purchaseid and timestocked=0");
			if($rss) {
				$shopid = $db->qstr($rss["shopid"]);
				$shop = $db->qstr($rss["shop"]);
				$productid = $db->qstr($rss["productid"]);
				$product = $db->qstr($rss["product"]);
				$spec = $db->qstr($rss["spec"]);
				$unit = $db->qstr($rss["unit"]);
				$number = $rss["number"]+0;
				 
			
				$stockid = $db->getone("select id from {$config->db_prefix}stocks where shopid=$shopid and productid=$productid");
			
				if(!$stockid)$sqlstr = "insert into {$config->db_prefix}stocks (shopid, shop, productid, product, spec, unit, stocks) values ($shopid, $shop, $productid, $product, $spec, $unit, $number)";
				else $sqlstr = "update {$config->db_prefix}stocks set stocks=stocks+$number where id=$stockid";
				$result = $db->execute($sqlstr);
				$this->_update_product_stocks($productid,$shopid);
				 
				$timestocked = time();
				$sqlstr = "update {$config->db_prefix}purchases set timestocked=$timestocked, suser='{$_SESSION['ADMIN_USER']}' where id=$purchaseid";
				$result = $db->execute($sqlstr);
			
				$this->update_paper_status($purchaseid,$rss['paper_id']);//判断是否全部入库并更新采购单状态
				
				return true;
			}
			return false;
		}
		
		function stockcancel(){
		    global $db, $segment, $config, $smarty;
		    $purchaseid = $db->qstr($_GET['purchases_id']);
		    $sqlstr = "update {$config->db_prefix}purchases set timestocked=-1 , suser='{$_SESSION['ADMIN_USER']}' where id=$purchaseid";
		    $result = $db->execute($sqlstr);
		    
		    $this->update_paper_status($purchaseid);//判断是否全部入库并更新采购单状态
		    
		    if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_admin}m=inventory&s=income.php":$_SERVER['HTTP_REFERER']));
		    
		    
		}
		
		function _update_product_stocks($productid,$shopid=0) {
		    global $db, $segment, $config, $smarty;
		    	
		    $stocks = $db->getone("select sum(stocks) from {$config->db_prefix}stocks where productid=$productid and shopid={$shopid}");
		    if(!$stocks) $stocks = 0;

		    /* $orders=$db->getone("select sum(number) from {$config->db_prefix}orders where productid={$productid} and timestocked=0 and type=0");
		    if(!$orders) $orders = 0; */
		    
		   
		    $result = $db->execute("update {$config->db_prefix}products set stocks=$stocks where product_sku_id=$productid and shopid={$shopid}");
		    return $result;
		}
		
		function sctock() {
		    global $db, $segment, $config, $smarty, $admin;
		    //if(!$admin->rights("income_view")) return;
		
		    if(!empty($segment[1]) && $segment[1]=="confirm") {
		        if(!$admin->rights("income_modify")) return;
		
		        $purchaseid = $db->qstr($segment[2]);
		        $rss = $db->getrow("select * from {$config->db_prefix}purchases where id=$purchaseid and timestocked=0");
		        if($rss) {
		            $shopid = $db->qstr($rss["shopid"]);
		            $shop = $db->qstr($rss["shop"]);
		            $productid = $db->qstr($rss["productid"]);
		            $product = $db->qstr($rss["product"]);
		            $spec = $db->qstr($rss["spec"]);
		            $unit = $db->qstr($rss["unit"]);
		            $number = $rss["number"]+0;
		            	
		            //
		            $stockid = $db->getone("select id from {$config->db_prefix}stocks where shopid=$shopid and productid=$productid");
		            if(!$stockid)$sqlstr = "insert into {$config->db_prefix}stocks (shopid, shop, productid, product, spec, unit, stocks) values ($shopid, $shop, $productid, $product, $spec, $unit, $number)";
		            else $sqlstr = "update {$config->db_prefix}stocks set stocks=stocks+$number where id=$stockid";
		            $result = $db->execute($sqlstr);
		            $this->_update_product_stocks($productid);
		            	
		            $timestocked = time();
		            $sqlstr = "update {$config->db_prefix}purchases set timestocked=$timestocked where id=$purchaseid";
		            $result = $db->execute($sqlstr);
		            if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_index}admin/stocks/income":$_SERVER['HTTP_REFERER']));
		        }
		    }
		    	
		    elseif(!empty($segment[1]) && $segment[1]=="cancel") {
		        if(!$admin->rights("income_modify")) return;
		
		        $purchaseid = $db->qstr($segment[2]);
		        $rss = $db->getrow("select * from {$config->db_prefix}purchases where id=$purchaseid and timestocked!=0");
		        if($rss) {
		            $shopid = $db->qstr($rss["shopid"]);
		            $productid = $db->qstr($rss["productid"]);
		            $number = $rss["number"]+0;
		            	
		            //
		            $stock = $db->getrow("select * from {$config->db_prefix}stocks where shopid=$shopid and productid=$productid");
		            if(!$stock) $errors["unexisted_product"] = true;
		            else if($stock["stocks"]<$number) $errors["notenough_stocks"] = true;
		            else if($stock["stocks"]==$number) $sqlstr = "delete from {$config->db_prefix}stocks where id=". $stock['id'];
		            else $sqlstr = "update {$config->db_prefix}stocks set stocks=stocks-$number where id=". $stock['id'];
		            	
		            if(empty($errors)) {
		                $result = $db->execute($sqlstr);
		                $this->_update_product_stocks($productid);
		                $sqlstr = "update {$config->db_prefix}purchases set timestocked=0 where id=$purchaseid";
		                $result = $db->execute($sqlstr);
		                if($result) header("location:".(empty($_SERVER['HTTP_REFERER'])?"{$config->site_index}admin/stocks/income":$_SERVER['HTTP_REFERER']));
		            }
		            	
		            if(!empty($errors)) $smarty->assign("errors", $errors);
		        }
		    }
		    	
		}

		/**
		 * 更新采购单状态（采购完成，状态置为9）
		 * @param unknown $paper_id
		 */
		private function update_paper_status($purchaseid,$paper_id=0){
			global $db,$config;
			$res = array();
			if($paper_id==0){
				$rss = $db->getrow("select paper_id from {$config->db_prefix}purchases where id=$purchaseid");
				$paper_id = $rss['paper_id'];
			}
			$sql = "select id from {$config->db_prefix}purchases where paper_id=$paper_id and timestocked not between 1 and 9999999999 and timestocked<>-1";
			$res = $db->GetArray($sql);
			
			if(empty($res)){
				$sql = "update {$config->db_prefix}purchases_paper set status=9 where id=$paper_id";
				$db->query($sql);
			}
		}

}
?>